<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>中国梦想游 - 我的车票</title>
    <link rel="stylesheet" type="text/css" href="/home/css/style.min.css?v=3.0.0">
    <link rel="stylesheet" type="text/css" href="/admin/css/style1.css">
    <link rel="stylesheet" type="text/css" href="/admin/css/style2.css">
    <link rel="stylesheet" type="text/css" href="/home/css/common.css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/public.css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/style.css"/>
    <link rel="stylesheet" type="text/css" href="/home/css/mygrxx.css"/>
    <link href="/home/fonts/iconfont.css" rel="stylesheet"/>
    <link rel="stylesheet" href="/home/css/ticket_index_v70003.css"/>
    <style>
        /* 页面布局样式 */
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }

        /* 确保主体内容占用剩余空间 */
        .Bott {
            flex: 1;
            padding-bottom: 15px; /* 进一步减少底部间距 */
        }

        /* 确保内容区域可滚动 */
        .panel-border {
            width: 100%;
            min-height: 450px;
            max-height: calc(100vh - 180px); /* 进一步减少高度 */
            overflow-y: auto; /* 添加垂直滚动条 */
            padding: 10px 0;
        }

        /* 空状态样式优化 */
        .empty {
            text-align: center;
            padding: 40px 0; /* 进一步减少空状态的上下内边距 */
            color: #999;
            font-size: 16px;
        }

        /* 车票列表滚动区域样式 */
        .ticket-scroll-container {
            max-height: calc(100vh - 220px); /* 进一步减少最大高度 */
            overflow-y: auto;
            overflow-x: hidden;
            padding: 3px 0;
        }

        /* 车票项之间的间距 */
        .order-panel-personal {
            margin-bottom: 10px; /* 进一步减少车票项之间的间距 */
        }

        .order-panel-personal:last-child {
            margin-bottom: 15px; /* 进一步减少最后一项的底部间距 */
        }

        /* 自定义滚动条样式 */
        .ticket-scroll-container::-webkit-scrollbar {
            width: 8px;
        }

        .ticket-scroll-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        .ticket-scroll-container::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        .ticket-scroll-container::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 添加页脚文字居中样式 */
        .bottom-info {
            text-align: center;
            margin: 0 auto;
            width: 100%;
        }

        /* 页面标题样式优化 */
        .address {
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        /* 面包屑导航样式 */
        .address a {
            color: #666;
            text-decoration: none;
        }

        .address a:hover {
            color: #007bff;
        }

        .address span {
            margin: 0 8px;
            color: #999;
        }

        /* 过期车票灰白展示样式 */
        .expired-ticket {
            filter: grayscale(100%);
            opacity: 0.6;
            background-color: #f8f9fa;
        }

        .expired-ticket .txt-bold {
            color: #6c757d !important;
        }

        .expired-ticket .txt-lg {
            color: #6c757d !important;
        }

        .expired-ticket .order-item-hd {
            background-color: #e9ecef;
        }

        .expired-ticket .order-item-date,
        .expired-ticket .order-item-num {
            color: #6c757d !important;
        }

    </style>
</head>
<body>
<!------------------------------head------------------------------>
<!--引入顶部文件-->
<div id="header"></div>
<!------------------------------idea------------------------------>
<div class="address">
    <div class="wrapper clearfix">
        <a>当前位置：</a>
        <a href="/home/index.html" >首页</a><span>></span>
        <a href="/home/center/personal/info.html" >  个人中心</a><span>></span>
        <a href="" class="go">本人车票</a>
    </div>
</div><!------------------------------Bott------------------------------>
<div class="Bott">
    <!-- 删除左侧菜单，调整内容区域布局 -->
    <div class="wrapper" style="width: 1200px;margin: 0 auto;">
        <!-- 直接显示内容区域，无需左侧菜单 -->
        <div class="you" style="width: 100%;padding: 10px 50px 10px 20px">
            <div class="center-main">
                <div class="panel-border border-transparent ifpersonal" style="display: block;min-height: 600px;">
                    <div class="panel-tab">
                        <div class="tab-hd">
                            <ul class="tab-hd-list" id="order_tab">
                                <li class="active"><a href="javascript:void(0);">本人车票 </a></li>
                            </ul>
                        </div>
                    </div>

                    <!-- Vue实例挂载点 -->
                    <div id="ticketApp">

                        <div class="tab-bd">
                            <!-- 车票列表滚动容器 -->
                            <div class="ticket-scroll-container">
                                <!-- 订单列表 -->
                                <div class="order-panel-personal" v-for="ticket in tickets" :key="ticket.ticket_id" :class="{'expired-ticket': isTicketExpired(ticket)}">
                                    <!-- 本人车票 -->
                                    <div class="order-item middle">
                                    <div class="order-item-hd">
                                        <div class="order-item-date">{{ ticket.departure_date }} {{ ticket.dayOfWeek
                                            }}
                                        </div>
                                        <div class="order-item-num">订单号： {{ ticket.order_no }}</div>
                                    </div>
                                    <div class="order-item-bd">
                                        <table id="order_table" class="order-item-table">
                                            <colgroup>
                                                <col class="col-station" style="width: 100px;">
                                                <col class="col-info" style="width: 140px;">
                                                <col class="col-station" style="width: 160px;">
                                                <col class="col-time" style="width: 140px;">
                                                <col class="col-seat" style="width: 160px">
                                                <col class="col-seat-num" style="width: 200px">
                                                <col class="col-seat-num" style="width: 160px">
                                                <col style="width: 100px">
                                                <col>
                                            </colgroup>
                                            <tbody>
                                            <tr>
                                                <td style="text-align: center; padding: 12px;">
                                                    <div class="txt-blg txt-bold" style="font-size: 18px;">{{ ticket.train_number }}</div>
                                                </td>
                                                <td style="text-align: center; padding: 12px">
                                                    <div class="txt-lg txt-bold" style="font-size: 16px;">{{ ticket.start_station }}</div>
                                                    <div class="mt" style="font-size: 14px;">{{ ticket.start_time }}开</div>
                                                </td>
                                                <td>
                                                    <div class="order-info-ticket"
                                                         style="height: 70px; background-position: center 16px; padding: 8px;">
                                                        <div class="ticket-about"
                                                             style="height: 30px; line-height: 30px;"></div>
                                                        <div class="mt" style="height: 30px; line-height: 30px;"><span
                                                                class="label-txt is-default" style="font-size: 14px;">车票当日当次有效</span>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="txt-lg txt-bold">{{ ticket.end_station }}</div>
                                                    <div class="mt">{{ ticket.arrive_time }}到</div>
                                                </td>
                                                <td>
                                                    <div class="txt-bold">
                                                        {{ ticket.seatType ? ticket.seatType.seat_type_name : '' }}
                                                    </div>
                                                    <div class="mt">{{ ticket.carriage_number }}车 {{ ticket.seat_number
                                                        }}号
                                                    </div>
                                                </td>
                                                <td style="font-size: 14px">
                                                    <div>身份证号</div>
                                                    <div class="mt">{{ ticket.card_code }}</div>
                                                </td>
                                                <td style="text-align: center">
                                                    <div>{{ getTicketTypeText(ticket.ticket_type) }}</div>
                                                    <div><span class="txt-price ml-sm"
                                                               style="margin-top: 8px">￥{{ ticket.ticket_price }}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div>
                                                        <span>{{ getTicketStatusText(ticket.ticket_status) }}</span>
                                                    </div>
                                                </td>
                                                <td>
                                                    <div style="display: flex; gap: 12px; justify-content: center; padding: 8px 0;">
                                                        <a v-if="ticket.ticket_status == 1" href="javascript:;"
                                                           class="btn btn-primary refund_ticket" style="height: 44px; padding: 0 24px; background-color: #dc3545; color: white; border-radius: 6px; text-decoration: none; transition: all 0.2s; font-size: 14px; font-weight: 500; display: inline-flex; align-items: center; justify-content: center;"
                                                           @click="refund(ticket.ticket_id, ticket)">退票</a>
                                                        <a v-if="ticket.ticket_status == 1" href="javascript:;"
                                                           class="btn btn-primary change_ticket" style="height: 44px; padding: 0 24px; background-color: #28a745; color: white; border-radius: 6px; text-decoration: none; transition: all 0.2s; font-size: 14px; font-weight: 500; display: inline-flex; align-items: center; justify-content: center;"
                                                           @click="changeTicket(ticket.ticket_id, ticket)">改签</a>
                                                    </div>
                                                </td>
                                            </tr>

                                            <tr>
                                                <td colspan="9" class="order-operation">
                                                    <div class="pull-left">
                                                        <span class="label-ticket-form">线上购买</span>
                                                        <span class="label-ticket-form">非现金支付</span>
                                                    </div>
                                                    <div class="btn-right pull-right">
                                                    </div>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    </div>
                                </div>
                            </div>
                            <!-- 加载中状态 -->
                            <div v-if="loading" class="empty">加载中...</div>

                            <!-- 空状态 -->
                            <div v-else-if="tickets.length === 0" class="empty">暂无车票信息</div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--引入底部footer.html文件-->
<div id="footer"></div>

<!-- 引入Vue和axios -->
<script src="/home/js/vue.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/axios.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/public.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/user.js" type="text/javascript" charset="utf-8"></script>
<script src="/home/js/config.js"></script>

<script>
    // 在DOM加载完成后创建Vue实例
    document.addEventListener('DOMContentLoaded', function () {
        // 创建Vue实例并保存到全局变量中
        let vueInstance = new Vue({
            el: '#ticketApp',
            data: {
                tickets: [],
                loading: false,
                stationList: {}, // 存储车站ID和名称的映射
                loadingStations: true // 车站数据加载状态
            },
            mounted() {
                this.loadStations();
                this.loadHeaderFooter();
            },
            methods: {
                // 加载车站列表
                loadStations() {
                    this.loadingStations = true;
                    axios.get('/admin/train_number/findStationList')
                        .then(response => {
                            // 添加更详细的响应结构检查
                            if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
                                // 构建车站ID到车站名的映射，同时尝试不同的ID字段名
                                response.data.data.forEach(station => {
                                    // 尝试不同的ID字段名，确保能正确匹配
                                    const stationId = station.id || station.stationId || station.station_id;
                                    const stationName = station.name || station.stationName || station.station_name;
                                    if (stationId && stationName) {
                                        this.stationList[stationId] = stationName;
                                    }
                                });
                            } else {
                                console.error('车站列表数据格式不正确:', response.data);
                            }
                            // 无论是否成功获取车站列表，都继续加载车票
                            this.loadTickets();
                        })
                        .catch(error => {
                            console.error('获取车站列表错误:', error);
                            // 即使获取车站列表失败，也继续加载车票
                            this.loadTickets();
                        })
                        .finally(() => {
                            this.loadingStations = false;
                        });
                },

                // 加载车票列表
                loadTickets() {
                    this.loading = true;
                    const userId = localStorage.getItem('USER_ID') || sessionStorage.getItem('userId');

                    if (!userId) {
                        alert('请先登录');
                        this.loading = false;
                        return;
                    }

                    // 加载所有车票，不使用分页
                    axios.get('/admin/ticket_manage/listByUserId', {
                        params: {
                            userId: userId
                        }
                    })
                        .then(response => {
                            if (response.data && response.data.code === 200) {
                                // 适配新的数据结构并进行必要的数据映射
                                const processedTickets = response.data.data.map(ticket => {
                                    // 解析日期时间
                                    const departureDateObj = new Date(ticket.departureTime);
                                    const arrivalDateObj = new Date(ticket.arrivalTime);

                                    // 获取星期几
                                    const days = ['日', '一', '二', '三', '四', '五', '六'];
                                    const dayOfWeek = `星期${days[departureDateObj.getDay()]}`;

                                    // 格式化日期为YYYY-MM-DD
                                    const formatDate = (date) => {
                                        return date.getFullYear() + '-' +
                                            String(date.getMonth() + 1).padStart(2, '0') + '-' +
                                            String(date.getDate()).padStart(2, '0');
                                    };

                                    // 格式化时间为HH:mm
                                    const formatTime = (date) => {
                                        return String(date.getHours()).padStart(2, '0') + ':' +
                                            String(date.getMinutes()).padStart(2, '0');
                                    };

                                    // 判断是否跨天
                                    const isNextDay = arrivalDateObj.toDateString() !== departureDateObj.toDateString();

                                    // 格式化到达时间，如果跨天则添加+1标记
                                    const formattedArriveTime = formatTime(arrivalDateObj) + (isNextDay ? '（次日）' : '');

                                    // 身份证号码脱敏处理
                                    const maskIdCard = (idCard) => {
                                        if (!idCard) return '';
                                        return idCard.slice(0, 4) + '***********' + idCard.slice(-4);
                                    };

                                    // 乘客类型映射为证件类型
                                    const getPassengerTypeText = (type) => {
                                        const typeMap = {
                                            0: '成人',
                                            1: '儿童',
                                            2: '学生',
                                            3: '军人'
                                        };
                                        return typeMap[type] || '成人';
                                    };

                                    // 获取车站名称，添加更健壮的映射逻辑
                                    const getStationName = (stationId) => {
                                        // 尝试直接匹配和字符串转换匹配
                                        const name = this.stationList[stationId] ||
                                                    this.stationList[stationId.toString()] ||
                                                    `车站${stationId}`;
                                        return name;
                                    };

                                    return {
                                        // 映射字段
                                        ticket_id: ticket.ticketId,
                                        train_number: '车次' + ticket.trainNumberId, // 使用实际车次ID
                                        // 尝试不同的字段名以确保正确获取车站ID
                                        start_station: getStationName(ticket.startStationId || ticket.start_station_id || ticket.startStation), // 使用车站名称
                                        start_time: formatTime(departureDateObj),
                                        end_station: getStationName(ticket.arrivalStationId || ticket.arrival_station_id || ticket.arrivalStation), // 使用车站名称
                                        arrive_time: formattedArriveTime, // 添加了跨天标记
                                        departure_date: formatDate(departureDateObj),
                                        dayOfWeek: dayOfWeek,
                                        order_no: ticket.orderId || ticket.order_no || ticket.ticketId, // 使用订单ID优先，其次order_no，最后ticketId
                                        seatType: {
                                            seat_type_name: this.getCarriageTypeText(ticket.carriageType)
                                        },
                                        carriage_number: ticket.carriageNumber, // 使用实际车厢号
                                        seat_number: ticket.seatNumber, // 使用实际座位号
                                        card_type: getPassengerTypeText(ticket.passengerType), // 使用实际乘客类型
                                        card_code: maskIdCard(ticket.idCard), // 使用实际身份证号（已脱敏）
                                        ticket_type: ticket.passengerType, // 使用乘客类型作为票种
                                        ticket_price: ticket.ticketPrice,
                                        ticket_status: ticket.ticketStatus
                                    };
                                });

                                this.tickets = processedTickets;
                            } else {
                                alert('获取车票列表失败: ' + (response.data ? response.data.message : '未知错误'));
                                // 清空数据
                                this.tickets = [];
                            }
                        })
                        .catch(error => {
                            console.error('获取车票列表错误:', error);
                            alert('网络错误，请稍后重试');
                            // 清空数据
                            this.tickets = [];
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                },
                // 获取车厢类型文本
                getCarriageTypeText(type) {
                    const typeMap = {
                        1: '硬座',
                        2: '硬卧',
                        3: '软卧',
                        4: '二等座',
                        5: '一等座',
                        6: '商务座'
                    };
                    return typeMap[type] || '未知座位类型';
                },

                // 判断车票是否过期（到达时间超过当前时间）
                isTicketExpired(ticket) {
                    try {
                        // 构建到达时间（结合出发日期和到达时间）
                        const arrivalDateTimeStr = `${ticket.departure_date} ${ticket.arrive_time.replace('（次日）', '')}`;
                        let arrivalDateTime = new Date(arrivalDateTimeStr);

                        // 如果到达时间包含"（次日）"，说明跨天了
                        if (ticket.arrive_time.includes('（次日）')) {
                            arrivalDateTime.setDate(arrivalDateTime.getDate() + 1);
                        }

                        // 获取当前时间
                        const now = new Date();

                        // 比较到达时间和当前时间
                        return arrivalDateTime < now;
                    } catch (error) {
                        console.error('判断车票是否过期时出错:', error);
                        return false; // 出错时默认为未过期
                    }
                },

                // 退票功能
                refund(ticketId, ticket) {
                    // 检查用户是否登录
                    const userId = localStorage.getItem('user_id') || localStorage.getItem('USER_ID') || sessionStorage.getItem('userId') || '';
                    if (!userId) {
                        alert('用户未登录，无法执行退票操作');
                        return;
                    }

                    // 确认退票
                    if (confirm('确定要退这张票吗？')) {
                        // 根据后端接口要求，构造正确的URL路径（注意：后端接口路径应该是/cancelTicket/{ticketId}/{orderId}/{userId}）
                        // 使用字符串拼接而非模板字符串，避免解析问题
                        const url = '/home/order/cancelTicket/' + ticketId + '/' + ticket.order_no + '/' + userId;
                        console.log('退票请求URL:', url); // 调试输出
                        console.log('ticketId:', ticketId, 'orderId:', ticket.order_no, 'userId:', userId); // 调试输出

                        axios.put(url)
                            .then(response => {
                                if (response.data && response.data.code === 200) {
                                    alert('退票成功！');
                                    // 重新加载车票列表
                                    this.loadTickets();
                                } else {
                                    alert('退票失败：' + (response.data ? response.data.message : '未知错误'));
                                }
                            })
                            .catch(error => {
                                console.error('退票错误:', error);
                                alert('网络错误，请稍后重试');
                            });
                    }
                },

                // 改签功能
                changeTicket(ticketId, ticket) {
                    // 检查用户是否登录
                    const userId = localStorage.getItem('user_id') || localStorage.getItem('USER_ID') || sessionStorage.getItem('userId') || '';
                    if (!userId) {
                        alert('用户未登录，无法执行改签操作');
                        return;
                    }

                    // 检查车票状态
                    if (ticket.ticket_status != 1) {
                        alert('只有已购买且未使用的车票才能改签');
                        return;
                    }

                    // 创建改签弹窗
                    this.showChangeTicketModal(ticket);
                },

                // 显示改签弹窗
                showChangeTicketModal(ticket) {
                    // 创建模态框HTML - 简洁实用版
                    const modalHtml = `
                        <div id="changeTicketModal" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; justify-content: center; align-items: center;">
                            <div style="background: white; border-radius: 8px; width: 90%; max-width: 900px; max-height: 90%; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.15);">

                                <!-- 头部 -->
                                <div style="background: #f8f9fa; padding: 20px; border-bottom: 1px solid #dee2e6; display: flex; justify-content: space-between; align-items: center;">
                                    <h3 style="margin: 0; color: #333; font-size: 18px;">改签车票</h3>
                                    <button onclick="document.getElementById('changeTicketModal').remove()"
                                            style="background: none; border: none; font-size: 24px; cursor: pointer; color: #6c757d; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 4px;">
                                        ×</button>
                                </div>

                                <!-- 内容区域 -->
                                <div style="padding: 20px; max-height: 70vh; overflow-y: auto;">
                                    <!-- 原车票信息 -->
                                    <div style="background: #f8f9fa; padding: 15px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #dee2e6;">
                                        <h4 style="margin: 0 0 10px 0; color: #495057; font-size: 14px; font-weight: bold;">原车票信息</h4>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                                            <div>
                                                <span style="color: #6c757d; font-size: 12px;">车次：</span>
                                                <span style="font-weight: bold;">${ticket.train_number}</span>
                                            </div>
                                            <div>
                                                <span style="color: #6c757d; font-size: 12px;">行程：</span>
                                                <span style="font-weight: bold;">${ticket.start_station} → ${ticket.end_station}</span>
                                            </div>
                                            <div>
                                                <span style="color: #6c757d; font-size: 12px;">出发时间：</span>
                                                <span style="font-weight: bold;">${ticket.departure_date} ${ticket.dayOfWeek} ${ticket.start_time}</span>
                                            </div>
                                            <div>
                                                <span style="color: #6c757d; font-size: 12px;">座位信息：</span>
                                                <span style="font-weight: bold;">${ticket.seatType.seat_type_name} ${ticket.carriage_number}车 ${ticket.seat_number}号</span>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 重新选择行程信息 -->
                                    <div style="background: #fff; padding: 20px; border: 1px solid #dee2e6; border-radius: 4px; margin-bottom: 20px;">
                                        <h4 style="margin: 0 0 15px 0; color: #495057; font-size: 14px; font-weight: bold;">重新选择行程信息</h4>

                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                            <div>
                                                <label style="display: block; margin-bottom: 5px; color: #495057; font-size: 13px; font-weight: 500;">出发站：</label>
                                                <select id="newStartStation" style="width: 100%; padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 14px;">
                                                    <option value="">请选择出发站</option>
                                                </select>
                                            </div>
                                            <div>
                                                <label style="display: block; margin-bottom: 5px; color: #495057; font-size: 13px; font-weight: 500;">到达站：</label>
                                                <select id="newEndStation" style="width: 100%; padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 14px;">
                                                    <option value="">请选择到达站</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                            <div>
                                                <label style="display: block; margin-bottom: 5px; color: #495057; font-size: 13px; font-weight: 500;">出发日期：</label>
                                                <input type="date" id="newDate" style="width: 100%; padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 14px;"
                                                       min="${ticket.departure_date}" value="${ticket.departure_date}">
                                            </div>
                                            <div>
                                                <label style="display: block; margin-bottom: 5px; color: #495057; font-size: 13px; font-weight: 500;">出发时间段：</label>
                                                <select id="newTimeRange" style="width: 100%; padding: 8px 12px; border: 1px solid #ced4da; border-radius: 4px; font-size: 14px;">
                                                    <option value="">全部时间段</option>
                                                    <option value="06:00-12:00">上午 (06:00-12:00)</option>
                                                    <option value="12:00-18:00">下午 (12:00-18:00)</option>
                                                    <option value="18:00-24:00">晚上 (18:00-24:00)</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div style="display: flex; align-items: center; gap: 10px;">
                                            <button type="button" id="searchTrainsBtn"
                                                    style="padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">
                                                查询可改签车次
                                            </button>
                                            <small style="color: #6c757d;">如不修改站点或时间，将使用原行程信息查询</small>
                                        </div>
                                    </div>

                                    <!-- 可改签车次 -->
                                    <div style="background: #fff; padding: 15px; border: 1px solid #dee2e6; border-radius: 4px;">
                                        <h4 style="margin: 0 0 10px 0; color: #495057; font-size: 14px; font-weight: bold;">可改签车次</h4>
                                        <div id="availableTrains" style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 4px; padding: 15px;">
                                            <p style="color: #6c757d; text-align: center; margin: 0;">请选择新的行程信息后查询可改签车次...</p>
                                        </div>
                                    </div>
                                </div>

                                <!-- 底部按钮 -->
                                <div style="background: #f8f9fa; padding: 15px 20px; display: flex; gap: 10px; justify-content: flex-end; border-top: 1px solid #dee2e6;">
                                    <button type="button" onclick="document.getElementById('changeTicketModal').remove()"
                                            style="padding: 8px 16px; border: 1px solid #6c757d; background: white; color: #6c757d; border-radius: 4px; cursor: pointer; font-size: 14px;">取消</button>
                                    <button type="button" id="confirmChangeBtn"
                                            style="padding: 8px 16px; background: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;" disabled>确认改签</button>
                                </div>
                            </div>
                        </div>
                    `;

                    // 将模态框添加到页面
                    document.body.insertAdjacentHTML('beforeend', modalHtml);

                    // 初始化车站选择
                    this.initStationSelection(ticket);

                    // 绑定查询按钮事件
                    document.getElementById('searchTrainsBtn').addEventListener('click', () => {
                        this.searchAvailableTrains(ticket);
                    });

                    // 绑定确认按钮事件 - 使用更直接的方法
                    const vm = this; // 保存Vue实例的引用

                    // 直接设置按钮的onclick事件
                    setTimeout(() => {
                        const confirmBtn = document.getElementById('confirmChangeBtn');
                        // console.log('寻找确认改签按钮...');
                        if (confirmBtn) {
                            // console.log('找到确认改签按钮，绑定事件');
                            // console.log('按钮状态:', confirmBtn.disabled);
                            // console.log('按钮样式:', confirmBtn.style.cssText);

                            // 修复：只使用一种事件绑定方式，避免重复调用
                            confirmBtn.onclick = function(e) {
                                // console.log('确认改签按钮被点击！按钮状态:', this.disabled);
                                // console.log('ticket对象:', ticket);
                                // console.log('事件对象:', e);
                                e.preventDefault();
                                e.stopPropagation();
                                vm.confirmChangeTicket(ticket);
                            };
                        } else {
                            // console.log('未找到确认改签按钮');
                        }
                    }, 100);
                },

                // 初始化车站选择
                initStationSelection(ticket) {
                    const startStationSelect = document.getElementById('newStartStation');
                    const endStationSelect = document.getElementById('newEndStation');

                    // 异步加载车站列表
                    this.loadStationList().then(stations => {
                        // 清空并重新填充站点选择
                        startStationSelect.innerHTML = '<option value="">请选择出发站</option>';
                        endStationSelect.innerHTML = '<option value="">请选择到达站</option>';

                        stations.forEach(station => {
                            // 使用正确的字段名：stationName
                            const stationName = station.stationName || station.station_name || station.name;
                            const stationId = station.stationId || station.station_id || station.id;

                            // 如果有ID则使用ID作为value，否则使用名称作为value
                            const value = stationId || stationName;

                            const startOption = new Option(stationName, value);
                            const endOption = new Option(stationName, value);
                            startStationSelect.add(startOption);
                            endStationSelect.add(endOption);
                        });

                        // 恢复原选择（通过车站名称匹配选项的显示文本）
                        Array.from(startStationSelect.options).forEach(option => {
                            if (option.textContent === ticket.start_station || option.value === ticket.start_station) {
                                startStationSelect.value = option.value;
                            }
                        });
                        Array.from(endStationSelect.options).forEach(option => {
                            if (option.textContent === ticket.end_station || option.value === ticket.end_station) {
                                endStationSelect.value = option.value;
                            }
                        });
                    });
                },

                // 加载车站列表
                loadStationList() {
                    return new Promise((resolve, reject) => {
                        if (this.stations && this.stations.length > 0) {
                            resolve(this.stations);
                            return;
                        }

                        // 从本地存储或API获取车站列表
                        axios.get('/admin/train_number/findStationList')
                            .then(response => {
                                if (response.data && response.data.code === 200) {
                                    this.stations = response.data.data;
                                    resolve(this.stations);
                                } else {
                                    // 如果API失败，使用默认车站列表
                                    const defaultStations = [
                                        {station_name: '北京南'},
                                        {station_name: '上海虹桥'},
                                        {station_name: '广州南'},
                                        {station_name: '深圳北'},
                                        {station_name: '杭州东'},
                                        {station_name: '南京南'},
                                        {station_name: '武汉'},
                                        {station_name: '成都东'},
                                        {station_name: '西安北'},
                                        {station_name: '重庆北'}
                                    ];
                                    resolve(defaultStations);
                                }
                            })
                            .catch(error => {
                                console.error('获取车站列表失败:', error);
                                // 使用默认车站列表
                                const defaultStations = [
                                    {station_name: '北京南'},
                                    {station_name: '上海虹桥'},
                                    {station_name: '广州南'},
                                    {station_name: '深圳北'},
                                    {station_name: '杭州东'},
                                    {station_name: '南京南'},
                                    {station_name: '武汉'},
                                    {station_name: '成都东'},
                                    {station_name: '西安北'},
                                    {station_name: '重庆北'}
                                ];
                                resolve(defaultStations);
                            });
                    });
                },

                // 查询可改签车次
                searchAvailableTrains(originalTicket) {
                    const availableTrainsDiv = document.getElementById('availableTrains');
                    const confirmBtn = document.getElementById('confirmChangeBtn');

                    // 获取用户选择的信息
                    const startStationValue = document.getElementById('newStartStation').value;
                    const endStationValue = document.getElementById('newEndStation').value;
                    const newDate = document.getElementById('newDate').value || originalTicket.departure_date;
                    const timeRange = document.getElementById('newTimeRange').value;

                    // 使用车站ID进行查询，如果没有ID则使用车站名称
                    const startStation = startStationValue || originalTicket.start_station;
                    const endStation = endStationValue || originalTicket.end_station;

                    // 验证必填信息
                    if (!startStation || !endStation) {
                        alert('请选择出发站和到达站');
                        return;
                    }

                    if (startStation === endStation) {
                        alert('出发站和到达站不能相同');
                        return;
                    }

                    availableTrainsDiv.innerHTML = '<p style="text-align: center; padding: 20px;">查询中，请稍候...</p>';
                    confirmBtn.disabled = true;

                    // 构建查询参数 - 传递车站ID而不是车站名称
                    const params = {
                        startStationId: startStation,
                        endStationId: endStation,
                        date: newDate
                    };

                    if (timeRange) {
                        params.timeRange = timeRange;
                    }

                    // 调用API获取可改签车次
                    axios.get('/home/order/findTrainNumberByDateAndRoute', { params })
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            let trains = response.data.data || [];

                            // 如果有时间段限制，进行过滤
                            if (timeRange) {
                                const [startTime, endTime] = timeRange.split('-');
                                trains = trains.filter(train => {
                                    const departureTime = train.departureTime;
                                    return departureTime >= startTime && departureTime < endTime;
                                });
                            }

                            // 过滤掉原车次
                            trains = trains.filter(train => {
                                const originalTrainNumber = originalTicket.train_number.replace('车次', '');
                                // 确保类型一致：转换为字符串比较
                                return String(train.trainNumberId) !== String(originalTrainNumber);
                            });

                            this.displayAvailableTrains(trains, availableTrainsDiv, confirmBtn);
                        } else {
                            availableTrainsDiv.innerHTML = '<p style="color: #999; text-align: center;">暂无可改签的车次</p>';
                        }
                    })
                    .catch(error => {
                        console.error('获取可改签车次错误:', error);
                        availableTrainsDiv.innerHTML = '<p style="color: #999; text-align: center;">网络错误，请稍后重试</p>';
                    });
                },

                // 格式化时间函数
                formatDateTime(dateTimeStr) {
                    if (!dateTimeStr) return '--';
                    try {
                        const date = new Date(dateTimeStr);
                        const month = String(date.getMonth() + 1).padStart(2, '0');
                        const day = String(date.getDate()).padStart(2, '0');
                        const hours = String(date.getHours()).padStart(2, '0');
                        const minutes = String(date.getMinutes()).padStart(2, '0');
                        return `${month}-${day} ${hours}:${minutes}`;
                    } catch (error) {
                        return dateTimeStr; // 如果解析失败，返回原始字符串
                    }
                },

                // 计算历时函数
                calculateDuration(departureTime, arrivalTime) {
                    if (!departureTime || !arrivalTime) return '--';
                    try {
                        const dep = new Date(departureTime);
                        const arr = new Date(arrivalTime);

                        let diff = arr - dep; // 毫秒差
                        if (diff < 0) {
                            // 如果到达时间小于出发时间，说明跨天了
                            diff += 24 * 60 * 60 * 1000;
                        }

                        const hours = Math.floor(diff / (60 * 60 * 1000));
                        const minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000));

                        return `${hours}小时${minutes}分钟`;
                    } catch (error) {
                        return '--';
                    }
                },

                // 获取票价函数（使用API返回的ticketPrice字段）
                getTrainPrice(train, seatType) {
                    // 如果API返回了ticketPrice价格，使用返回的价格
                    if (train.ticketPrice !== undefined && train.ticketPrice !== null) {
                        return train.ticketPrice;
                    }

                    // 如果没有价格数据，根据座位类型返回默认价格
                    const defaultPrices = {
                        1: 500, // 一等座
                        2: 300, // 二等座
                        3: 800, // 商务座
                        4: 150, // 硬座
                        5: 400, // 硬卧
                        6: 600  // 软卧
                    };

                    return defaultPrices[seatType] || 200; // 默认价格
                },

                // 显示可改签车次
                displayAvailableTrains(trains, container, confirmBtn) {
                    if (!trains || trains.length === 0) {
                        container.innerHTML = '<p style="color: #999; text-align: center;">暂无可改签的车次</p>';
                        return;
                    }

                    let html = '<table style="width: 100%; border-collapse: collapse; margin-bottom: 10px;">';
                    html += '<tr style="background: #f8f9fa;"><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">选择</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">车次</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">座位类型</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">出发时间</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">到达时间</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">历时</th><th style="padding: 10px; border: 1px solid #dee2e6; text-align: left;">票价</th></tr>';

                    trains.forEach((train, index) => {
                        const radioId = `train_${index}`;
                        const isAvailable = train.remainingTickets > 0;

                        // 处理座位类型显示
                        const getSeatTypeText = (carriageType) => {
                            const seatTypeMap = {
                                1: '一等座',
                                2: '二等座',
                                3: '商务座',
                                4: '硬座',
                                5: '硬卧',
                                6: '软卧'
                            };
                            return seatTypeMap[carriageType] || `类型${carriageType}`;
                        };

                        html += `<tr style="background-color: ${isAvailable ? 'white' : '#f8f9fa'}; ${!isAvailable ? 'opacity: 0.6;' : ''}"
                                     onclick="${isAvailable ? `const radio = document.getElementById('${radioId}'); radio.checked = true; radio.dispatchEvent(new Event('change')); this.style.backgroundColor = '#e3f2fd'` : ''}"
                                     data-train-id="${train.trainNumberId}"
                                     data-price="${train.ticketPrice || this.getTrainPrice(train, train.carriageType)}"
                                     data-carriage-type="${train.carriageType}"
                                     data-departure-time="${train.departureTime}"
                                     data-arrival-time="${train.arrivalTime}"
                                     data-original-train='${JSON.stringify(train)}'>
                            <td style="padding: 8px; border: 1px solid #dee2e6;">
                                <input type="radio" name="selectTrain" id="${radioId}" value="${train.trainNumberId}" ${!isAvailable ? 'disabled' : ''}>
                                ${!isAvailable ? '<small style="color: #dc3545;">无票</small>' : ''}
                            </td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; font-weight: bold;">车次${train.trainNumberId}</td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; color: #333; font-weight: bold;">${getSeatTypeText(train.carriageType)}</td>
                            <td style="padding: 8px; border: 1px solid #dee2e6;">${this.formatDateTime(train.departureTime)}</td>
                            <td style="padding: 8px; border: 1px solid #dee2e6;">${this.formatDateTime(train.arrivalTime)}</td>
                            <td style="padding: 8px; border: 1px solid #dee2e6;">${this.calculateDuration(train.departureTime, train.arrivalTime)}</td>
                            <td style="padding: 8px; border: 1px solid #dee2e6; color: #dc3545; font-weight: bold;">￥${this.getTrainPrice(train, train.carriageType)}</td>
                        </tr>`;
                    });

                    html += '</table>';

                    const summaryHtml = `
                        <div style="background: #f8f9fa; padding: 10px; border-radius: 5px; font-size: 14px;">
                            <strong>查询结果：</strong>共找到 ${trains.length} 个可改签车次
                        </div>
                    `;

                    container.innerHTML = html + summaryHtml;

                    // 绑定单选框变化事件以启用/禁用确认按钮
                    const radioButtons = container.querySelectorAll('input[name="selectTrain"]');
                    radioButtons.forEach(radio => {
                        radio.addEventListener('change', () => {
                            const isChecked = document.querySelector('input[name="selectTrain"]:checked');
                            confirmBtn.disabled = !isChecked;

                            // 保存选择的车次信息到全局变量（保存完整的原始数据）
                            if (isChecked) {
                                const selectedRow = radio.closest('tr');
                                // 从行数据中获取完整的原始车次信息
                                const originalTrainData = JSON.parse(selectedRow.getAttribute('data-original-train'));
                                window.selectedTrainInfo = {
                                    selectedTrain: radio,
                                    // 保存完整的原始数据
                                    trainData: originalTrainData
                                };
                                console.log('保存选择的车次信息:', window.selectedTrainInfo);
                            }
                        });
                    });
                },

                // 加载头部和底部
                loadHeaderFooter() {
                    // 加载头部
                    $('#header').load('/home/header.html', function () {
                    });

                    // 加载底部
                    $('#footer').load('/home/footer.html', function () {
                    });
                },

                // 获取车站名称（通过ID或名称）
                getStationName(stationValue) {
                    if (!stationValue) {
                        return stationValue;
                    }

                    // 从stationList对象中查找车站名称
                    if (this.stationList && Object.keys(this.stationList).length > 0) {
                        // 尝试直接匹配
                        if (this.stationList[stationValue]) {
                            return this.stationList[stationValue];
                        }
                        // 尝试字符串转换匹配
                        if (this.stationList[stationValue.toString()]) {
                            return this.stationList[stationValue.toString()];
                        }
                    }

                    // 如果找不到匹配的，返回原值
                    return stationValue;
                },

                // 确认改签
                confirmChangeTicket(originalTicket) {
                    // 调试：查看所有单选框
                    const allRadioButtons = document.querySelectorAll('input[name="selectTrain"]');

                    // 使用保存的车次信息（不需要再从DOM中获取）
                    const selectedTrainInfo = window.selectedTrainInfo;
                    if (!selectedTrainInfo) {
                        alert('请先选择要改签的车次');
                        return;
                    }

                    // 验证是否有选中的车次（基于保存的信息）
                    if (!selectedTrainInfo) {
                        // 增强调试：检查是否有任何单选框被选中
                        let foundChecked = false;
                        allRadioButtons.forEach(radio => {
                            if (radio.checked) {
                                foundChecked = true;
                            }
                        });

                        if (!foundChecked) {
                            alert('没有找到选中的车次！请尝试重新选择。\n\n调试信息：\n- 找到' + allRadioButtons.length + '个单选框\n- 所有单选框都未选中\n- 请检查浏览器控制台查看详细信息');
                        } else {
                            alert('DOM查询异常！单选框已被选中但查询失败。\n\n调试信息：\n- 找到' + allRadioButtons.length + '个单选框\n- 某些单选框已被选中\n- 请刷新页面重试');
                        }
                        this.showInfoModal('提示', '请选择要改签的车次');
                        return;
                    }

                    // 使用保存的完整原始车次数据
                    const trainData = selectedTrainInfo.trainData;
                    const trainPrice = trainData.ticketPrice;
                    const carriageType = trainData.carriageType;
                    const departureTime = trainData.departureTime;
                    const arrivalTime = trainData.arrivalTime;
                    const trainNumberId = trainData.trainNumberId;

                    // 获取用户选择的所有信息
                    const startStationValue = document.getElementById('newStartStation').value;
                    const endStationValue = document.getElementById('newEndStation').value;

                    // 获取车站选择下拉框的文本值（显示文本）
                    const startStationSelect = document.getElementById('newStartStation');
                    const endStationSelect = document.getElementById('newEndStation');
                    const newStartStation = startStationValue ? startStationSelect.options[startStationSelect.selectedIndex].text : originalTicket.start_station;
                    const newEndStation = endStationValue ? endStationSelect.options[endStationSelect.selectedIndex].text : originalTicket.end_station;

                    // 尝试转换原车站ID为站名
                    const originalStartStation = this.getStationName(originalTicket.start_station);
                    const originalEndStation = this.getStationName(originalTicket.end_station);

                    const newDate = document.getElementById('newDate').value || originalTicket.departure_date;
                    const timeRange = document.getElementById('newTimeRange').value;

                    // 创建简洁的改签信息
                    const changeInfo = `请仔细核对改签信息：

🔴 原车票：
• 车次：${originalTicket.train_number}
• 行程：${originalStartStation} → ${originalEndStation}
• 时间：${originalTicket.departure_date} ${originalTicket.dayOfWeek} ${originalTicket.start_time}
• 座位：${originalTicket.seatType.seat_type_name} ${originalTicket.carriage_number}车 ${originalTicket.seat_number}号

⬇️ 改签为

🟢 新车票：
• 车次：${trainNumberId}
• 行程：${newStartStation} → ${newEndStation}
• 时间：${newDate} ${timeRange ? '(' + timeRange + ')' : ''}
• 座位：${this.getSeatTypeText(carriageType)}
• 票价：￥${trainPrice}

⚠️ 请确认改签信息，确认后无法撤销。`;

                    // 先关闭改签模态框，再弹出确认模态框（避免模态框叠加）
                    const changeModal = document.getElementById('changeTicketModal');
                    if (changeModal) {
                        changeModal.remove();
                    }

                    // 使用模态框确认改签
                    const vm = this; // 保存当前Vue实例的引用
                    this.showConfirmModal(
                        '确认改签',
                        changeInfo,
                        'confirmChangeTicketCallback',
                        null,
                        originalTicket // 传递originalTicket参数
                    );
                },

                // 获取座位类型文本
                getSeatTypeText(carriageType) {
                    const seatTypeMap = {
                        1: '一等座',
                        2: '二等座',
                        3: '商务座',
                        4: '硬座',
                        5: '硬卧',
                        6: '软卧'
                    };
                    return seatTypeMap[carriageType] || `类型${carriageType}`;
                },

                // 获取车票类型文本
                getTicketTypeText(type) {
                    const typeMap = {
                        0: '成人票',
                        1: '儿童票',
                        2: '学生票',
                        3: '优惠票'
                    };
                    return typeMap[type] || '未知票种';
                },

                // 获取车票状态文本
                getTicketStatusText(status) {
                    const statusMap = {
                        0: '未使用',
                        1: '已购买', // 添加状态1的映射
                        2: '已使用',
                        3: '已退票',
                        4: '已过期',
                        5: '已改签',
                        6: '已取消',
                        7: '退票中'
                    };
                    return statusMap[status] || '未知状态';
                },

                // 显示信息模态框
                showInfoModal(title, message, callback = null) {

                    const modalHtml = `
                        <div id="infoModal" style="
                            position: fixed;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                            background: rgba(0,0,0,0.5);
                            z-index: 10000;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        ">
                            <div style="
                                background: white;
                                padding: 0;
                                border-radius: 12px;
                                max-width: 500px;
                                width: 90%;
                                box-shadow: 0 8px 32px rgba(0,0,0,0.3);
                                animation: modalFadeIn 0.3s ease;
                            ">
                                <!-- 模态框头部 -->
                                <div style="
                                    padding: 24px 24px 16px 24px;
                                    border-bottom: 1px solid #eee;
                                    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
                                    border-radius: 12px 12px 0 0;
                                    color: white;
                                ">
                                    <div style="
                                        display: flex;
                                        align-items: center;
                                        gap: 12px;
                                    ">
                                        <div style="
                                            width: 24px;
                                            height: 24px;
                                            background: rgba(255,255,255,0.2);
                                            border-radius: 50%;
                                            display: flex;
                                            align-items: center;
                                            justify-content: center;
                                            font-size: 14px;
                                        ">
                                            ℹ️
                                        </div>
                                        <h3 style="margin: 0; font-size: 18px; font-weight: 600;">${title}</h3>
                                    </div>
                                </div>

                                <!-- 消息内容区域 -->
                                <div style="
                                    padding: 20px 24px;
                                    color: #495057;
                                    line-height: 1.6;
                                    white-space: pre-line;
                                ">
                                    ${message}
                                </div>

                                <!-- 按钮区域 -->
                                <div style="
                                    padding: 0 24px 24px 24px;
                                    text-align: right;
                                ">
                                    <button onclick="this.closest('#infoModal').remove()" style="
                                        padding: 10px 24px;
                                        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
                                        color: white;
                                        border: none;
                                        border-radius: 8px;
                                        cursor: pointer;
                                        font-size: 14px;
                                        font-weight: 500;
                                        box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
                                        transition: all 0.2s ease;
                                    " onmouseover="this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 12px rgba(0, 123, 255, 0.4)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0, 123, 255, 0.3)'">
                                        确定
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;

                    document.body.insertAdjacentHTML('beforeend', modalHtml);

                    // 如果有回调函数，在模态框关闭时执行
                    const modal = document.getElementById('infoModal');
                    modal.addEventListener('click', function(e) {
                        if (e.target === this) {
                            this.remove();
                            if (callback) callback();
                        }
                    });
                },

                // 显示确认模态框
                showConfirmModal(title, message, onConfirm, onCancel = null, originalTicket = null) {
                    // 先关闭可能存在的确认模态框（避免模态框叠加）
                    const existingModal = document.getElementById('confirmModal');
                    if (existingModal) {
                        existingModal.remove();
                    }
                    const modalHtml = `
                        <div id="confirmModal" style="
                            position: fixed;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                            background: rgba(0,0,0,0.5);
                            z-index: 10000;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        ">
                            <div style="
                                background: white;
                                padding: 0;
                                border-radius: 12px;
                                max-width: 700px;
                                width: 90%;
                                max-height: 80vh;
                                overflow-y: auto;
                                box-shadow: 0 8px 32px rgba(0,0,0,0.3);
                                animation: modalFadeIn 0.3s ease;
                            ">
                                <!-- 模态框头部 -->
                                <div style="
                                    padding: 24px 24px 16px 24px;
                                    border-bottom: 1px solid #eee;
                                    background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
                                    border-radius: 12px 12px 0 0;
                                    color: white;
                                ">
                                    <div style="
                                        display: flex;
                                        align-items: center;
                                        gap: 12px;
                                    ">
                                        <div style="
                                            width: 24px;
                                            height: 24px;
                                            background: rgba(255,255,255,0.2);
                                            border-radius: 50%;
                                            display: flex;
                                            align-items: center;
                                            justify-content: center;
                                            font-size: 14px;
                                        ">
                                            ℹ️
                                        </div>
                                        <h3 style="margin: 0; font-size: 18px; font-weight: 600;">${title}</h3>
                                    </div>
                                </div>

                                <!-- 消息内容区域 -->
                                <div style="
                                    padding: 20px 24px;
                                    color: #666;
                                    line-height: 1.6;
                                    white-space: pre-line;
                                    max-height: 60vh;
                                    overflow-y: auto;
                                ">
                                    <div style="
                                        margin-bottom: 16px;
                                        padding: 12px;
                                        background: #f8f9fa;
                                        border-radius: 8px;
                                        border-left: 4px solid #007bff;
                                    ">
                                        <div style="
                                            font-size: 14px;
                                            color: #495057;
                                            margin-bottom: 8px;
                                        ">
                                            💡 请仔细核对改签信息，确认后无法撤销
                                        </div>
                                    </div>
                                    ${message}
                                </div>

                                <!-- 按钮区域 -->
                                <div style="
                                    padding: 16px 24px 24px 24px;
                                    border-top: 1px solid #eee;
                                    background: #fafafa;
                                    border-radius: 0 0 12px 12px;
                                    display: flex;
                                    gap: 12px;
                                    justify-content: flex-end;
                                ">
                                    <button onclick="
                                        this.closest('#confirmModal').remove();
                                        ${onCancel ? 'window.ticketApp.' + onCancel + '();' : ''}
                                    " style="
                                        padding: 12px 24px;
                                        border: 1px solid #dee2e6;
                                        background: white;
                                        color: #6c757d;
                                        border-radius: 8px;
                                        cursor: pointer;
                                        font-size: 14px;
                                        font-weight: 500;
                                        transition: all 0.2s ease;
                                    " onmouseover="this.style.background='#f8f9fa'" onmouseout="this.style.background='white'">
                                        取消
                                    </button>
                                    <button onclick="handleConfirmClick(this)" data-callback="${onConfirm}" data-original-ticket='${originalTicket ? JSON.stringify(originalTicket) : 'null'}' style="
                                        padding: 10px 24px;
                                        background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
                                        color: white;
                                        border: none;
                                        border-radius: 8px;
                                        cursor: pointer;
                                        font-size: 14px;
                                        font-weight: 500;
                                        box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
                                        transition: all 0.2s ease;
                                    " onmouseover="this.style.transform='translateY(-1px)'; this.style.boxShadow='0 4px 12px rgba(0, 123, 255, 0.4)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 8px rgba(0, 123, 255, 0.3)'">
                                        确认
                                    </button>
                                </div>
                            </div>
                        </div>
                    `;



                    try {
                        document.body.insertAdjacentHTML('beforeend', modalHtml);

                        // 检查模态框是否真的存在
                        const modalCheck = document.getElementById('confirmModal');

                        // 添加动画样式
                        if (!document.getElementById('modalStyles')) {
                            const style = document.createElement('style');
                            style.id = 'modalStyles';
                            style.textContent = `
                                @keyframes modalFadeIn {
                                    from { opacity: 0; transform: scale(0.8) translateY(-20px); }
                                    to { opacity: 1; transform: scale(1) translateY(0); }
                                }
                            `;
                            document.head.appendChild(style);
                        }

                        // 点击背景关闭模态框
                        const modal = document.getElementById('confirmModal');
                        if (modal) {
                            modal.addEventListener('click', function(e) {
                                if (e.target === this) {
                                    this.remove();
                                    if (onCancel) {
                                        // 创建一个临时函数来调用onCancel
                                        window.ticketApp[onCancel] && window.ticketApp[onCancel]();
                                    }
                                }
                            });

                            // 设置originalTicket参数（如果有）
                            if (originalTicket) {
                                modal.setAttribute('data-original-ticket', JSON.stringify(originalTicket));
                            }
                        } else {
                            console.error('模态框元素未找到！');
                        }

                    } catch (error) {
                        console.error('添加模态框时出错:', error);
                    }
                },

                // 确认改签的回调函数
                confirmChangeTicketCallback(originalTicket) {
                    if (!originalTicket) {
                        this.showInfoModal('错误', '无法获取原票信息，请重新操作');
                        return;
                    }

                    // 检查是否有保存的车次选择信息
                    if (!window.selectedTrainInfo) {
                        this.showInfoModal('错误', '未找到选择的车次信息，请重新选择');
                        console.error('window.selectedTrainInfo 不存在');
                        return;
                    }

                    const userId = localStorage.getItem('user_id') || localStorage.getItem('USER_ID') || sessionStorage.getItem('userId') || '';
                    const selectedTrainInfo = window.selectedTrainInfo;
                    const newTrainId = selectedTrainInfo.trainId;

                    // 使用保存的车次信息（不需要再从DOM中获取）
                    const trainPrice = selectedTrainInfo.trainPrice;
                    const carriageType = selectedTrainInfo.carriageType;
                    const departureTime = selectedTrainInfo.departureTime;
                    const arrivalTime = selectedTrainInfo.arrivalTime;

                    // 获取用户选择的所有信息
                    const startStation = document.getElementById('newStartStation').value || originalTicket.start_station;
                    const endStation = document.getElementById('newEndStation').value || originalTicket.end_station;
                    const newDate = document.getElementById('newDate').value || originalTicket.departure_date;
                    const timeRange = document.getElementById('newTimeRange').value;

                    // 构建完整的改签参数，传递给后端
                    const changeParams = {
                        // 原票信息
                        ticketId: originalTicket.ticket_id,
                        userId: userId,
                        originalTrainNumber: originalTicket.train_number,
                        originalStartStation: originalTicket.start_station,
                        originalEndStation: originalTicket.end_station,
                        originalDate: originalTicket.departure_date,
                        originalSeatType: originalTicket.seatType.seat_type_name,
                        originalCarriageNumber: originalTicket.carriage_number,
                        originalSeatNumber: originalTicket.seat_number,

                        // 新票信息
                        newTrainId: newTrainId,
                        newDate: newDate,
                        newStartStation: startStation,
                        newEndStation: endStation,
                        newSeatType: carriageType,
                        newDepartureTime: departureTime,
                        newArrivalTime: arrivalTime,
                        newPrice: trainPrice,
                        newTimeRange: timeRange
                    };

                    // 调用改签API
                    axios.put('/home/order/changeTicket', changeParams)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.showInfoModal('改签成功', '您的车票已成功改签，原票已自动退票。', () => {
                                // 关闭模态框
                                document.getElementById('changeTicketModal').remove();
                                // 重新加载车票列表
                                this.loadTickets();
                            });
                        } else {
                            this.showInfoModal('改签失败', '改签失败：' + (response.data ? response.data.message : '未知错误'));
                        }
                    })
                    .catch(error => {
                        console.error('改签错误:', error);
                        this.showInfoModal('网络错误', '网络错误，请稍后重试');
                    });
                }
            }
        });

        // 正确保存Vue实例到全局变量
        window.ticketApp = vueInstance;

        // 将confirmChangeTicketCallback设置为全局函数，确保可以正确调用
        window.confirmChangeTicketCallback = function(originalTicket) {
            // 使用Vue实例的方法来调用，确保正确的上下文
            if (window.ticketApp && typeof window.ticketApp.confirmChangeTicketCallback === 'function') {
                window.ticketApp.confirmChangeTicketCallback.call(window.ticketApp, originalTicket);
            } else {
                console.error('Vue实例或方法不存在');
            }
        };

        // 全局函数：处理确认按钮点击事件（简化修复版本）
        window.handleConfirmClick = function(button) {
            console.log('=== handleConfirmClick 开始执行 ===');

            try {
                // 关闭确认模态框
                const modal = button.closest('#confirmModal') || document.getElementById('confirmModal');
                if (modal) {
                    modal.remove();
                }

                // 获取参数
                const originalTicketData = button.getAttribute('data-original-ticket');
                const callback = button.getAttribute('data-callback');

                console.log('获取到的参数:', { callback, originalTicketData });

                // 解析原票信息
                let parsedData = null;
                if (originalTicketData && originalTicketData !== 'null') {
                    try {
                        parsedData = JSON.parse(originalTicketData);
                        console.log('解析的原票信息:', parsedData);
                    } catch (e) {
                        console.error('解析原票信息失败:', e);
                        alert('数据解析错误，请重新操作');
                        return;
                    }
                }

                // 检查必要参数
                if (!callback) {
                    console.error('未找到回调函数名称');
                    alert('系统错误：未找到回调函数');
                    return;
                }

                if (!parsedData) {
                    console.error('原票信息缺失');
                    alert('原票信息缺失，请重新操作');
                    return;
                }

                // 检查全局的车次选择信息
                if (!window.selectedTrainInfo) {
                    console.error('未找到选择的车次信息');
                    alert('未找到选择的车次信息，请重新选择车次');
                    return;
                }

                console.log('选择的车次信息:', window.selectedTrainInfo);

                // 如果是改签回调，直接执行改签逻辑
                if (callback === 'confirmChangeTicketCallback') {
                    executeChangeTicketLogic(parsedData);
                } else {
                    console.error('未知的回调函数:', callback);
                    alert('系统错误：未知的操作类型');
                }

            } catch (error) {
                console.error('处理确认点击时发生错误:', error);
                alert('操作失败，请重试');
            }
        };

        // 独立的改签逻辑执行函数
        function executeChangeTicketLogic(originalTicket) {
            try {
                console.log('=== 开始执行改签逻辑 ===');

                const selectedTrainInfo = window.selectedTrainInfo;
                if (!selectedTrainInfo) {
                    console.error('选择的车次信息不存在');
                    alert('请先选择要改签的车次');
                    return;
                }

                // 获取用户ID
                const userId = localStorage.getItem('user_id') ||
                              localStorage.getItem('USER_ID') ||
                              sessionStorage.getItem('userId') || '';

                if (!userId) {
                    console.error('未找到用户ID');
                    alert('用户信息缺失，请重新登录');
                    return;
                }

                // 获取用户选择的所有信息（安全获取，避免空指针错误）
                const startStationElement = document.getElementById('newStartStation');
                const endStationElement = document.getElementById('newEndStation');
                const newDateElement = document.getElementById('newDate');
                const timeRangeElement = document.getElementById('newTimeRange');

                const startStation = startStationElement ? startStationElement.value : originalTicket.start_station;
                const endStation = endStationElement ? endStationElement.value : originalTicket.end_station;
                const newDate = newDateElement ? newDateElement.value : originalTicket.departure_date;
                const timeRange = timeRangeElement ? timeRangeElement.value : '';

                // 使用原始车次数据构建改签参数（保持与查询返回的格式一致）
                const selectedTrainData = selectedTrainInfo.trainData;
                if (!selectedTrainData) {
                    console.error('选择的车次原始数据不存在');
                    alert('选择的车次信息不完整，请重新选择');
                    return;
                }

                // 直接使用原始数据，不做任何转换
                const changeParams = {
                    // 直接传递选中的车次数据（与查询返回格式一致）
                    ticketId: selectedTrainData.ticketId,
                    trainNumberId: selectedTrainData.trainNumberId,
                    carriageType: selectedTrainData.carriageType,
                    startStationId: selectedTrainData.startStationId,
                    arrivalStationId: selectedTrainData.arrivalStationId,
                    departureTime: selectedTrainData.departureTime,
                    arrivalTime: selectedTrainData.arrivalTime,
                    ticketPrice: selectedTrainData.ticketPrice,
                    totalTickets: selectedTrainData.totalTickets,
                    remainingTickets: selectedTrainData.remainingTickets,
                    ticketStatus: selectedTrainData.ticketStatus,

                    // 原票信息（用于后端处理）
                    originalTicketId: originalTicket.ticket_id,
                    userId: userId
                };

                console.log('构建的改签参数:', changeParams);

                // 检查必要参数
                if (!changeParams.ticketId || !changeParams.userId || !changeParams.originalTicketId) {
                    console.error('必要参数缺失:', {
                        ticketId: !!changeParams.ticketId,
                        userId: !!changeParams.userId,
                        originalTicketId: !!changeParams.originalTicketId
                    });
                    alert('必要信息缺失，请重新操作');
                    return;
                }

                console.log('=== 发起改签请求 ===');

                // 构建改签参数 - 完整匹配ChangeTicketEntity实体类
                const changeTicketParams = {
                    // 改签基本信息
                    changeId: '', // 初始为空，后端生成
                    ticketId: originalTicket.ticket_id, // 原车票ID（需要传递）
                    orderId: originalTicket.order_no || originalTicket.orderId || originalTicket.ticket_id, // 订单ID（使用原车票记录中的orderId）

                    // 用户信息（必需）
                    userId: parseInt(userId),
                    username: localStorage.getItem('username') || localStorage.getItem('user_name') || '',

                    // 原票信息（必需）
                    originalTrainNumber: originalTicket.train_number.toString().replace(/^车次/, ''), // 去掉"车次"前缀
                    originalPrice: parseFloat(originalTicket.ticket_price || 0), // 使用原车票的ticket_price字段

                    // 新票信息（必需，使用选中车次的原始数据）
                    newTrainNumber: selectedTrainData.trainNumberId.toString(),
                    startStation: startStation,
                    endStation: endStation,
                    newPrice: parseFloat(selectedTrainData.ticketPrice || 0), // JavaScript数字类型

                    // 改签信息（必需）
                    changeFee: 0, // 改签费用由后端计算处理
                    applyTime: new Date().toISOString(), // JavaScript Date对象
                    reason: `改签申请：从 ${originalTicket.train_number} 改签为 ${selectedTrainData.trainNumberId}`,
                    status: 0, // 设置为待审核状态
                    processBy: '', // 初始为空，审核后设置

                    // 业务需要 - 新车票ID（必需）
                    newTicketId: selectedTrainData.ticketId, // 使用选中车次的ticketId作为新车票ID

                    // 可选字段
                    processTime: null, // 初始为空，审核后设置
                    remark: `用户申请改签，原票${originalTicket.train_number}改签为${selectedTrainData.trainNumberId}`
                };

                console.log('构建的改签参数:', changeTicketParams);

                // 验证车票ID字段
                console.log('=== 车票ID验证 ===');
                console.log('原车票ID:', originalTicket.ticket_id);
                console.log('订单ID:', changeTicketParams.orderId);
                console.log('原车票价格:', originalTicket.ticket_price);
                console.log('原车次号:', changeTicketParams.originalTrainNumber);
                console.log('==================');

                // 调用改签API - URL格式: /changeTicket/{userId}
                axios.put(`/home/order/changeTicket/${userId}`, changeTicketParams)
                    .then(response => {
                        console.log('改签API响应:', response);

                        if (response.data && response.data.code === 200) {
                            // 改签成功
                            // 后端返回格式可能是字符串订单号或包含orderNumber的对象
                            let orderNumber = null;

                            if (typeof response.data.data === 'string') {
                                // 直接返回订单号字符串
                                orderNumber = response.data.data;
                            } else if (response.data.data && response.data.data.orderNumber) {
                                // 返回包含orderNumber属性的对象
                                orderNumber = response.data.data.orderNumber;
                            }

                            if (orderNumber) {
                                // 有支付订单号，跳转到支付宝支付
                                console.log('改签成功，获得支付订单号:', orderNumber);

                                // 关闭改签模态框
                                const changeModal = document.getElementById('changeTicketModal');
                                if (changeModal) {
                                    changeModal.remove();
                                }

                                // 显示支付提示
                                if (window.ticketApp && typeof window.ticketApp.showInfoModal === 'function') {
                                    window.ticketApp.showInfoModal('改签成功', '改签成功，正在跳转到支付宝支付界面...');
                                } else {
                                    alert('改签成功，正在跳转到支付宝支付界面...');
                                }
                                // 跳转到支付宝支付页面
                                setTimeout(() => {
                                    // 跳转到支付页面，携带订单号
                                    // 成功，跳转到支付页面
                                    window.location.href = '/home/order/order_pay.html?order_id=' + response.data.data;
                                }, 1500);

                            } else {
                                // 无支付订单号（可能改签无差价或其他原因）
                                console.log('改签成功，无支付订单号');

                                if (window.ticketApp && typeof window.ticketApp.showInfoModal === 'function') {
                                    window.ticketApp.showInfoModal('改签成功', '您的车票已成功改签，原票已自动退票。', () => {
                                        // 关闭改签模态框
                                        const changeModal = document.getElementById('changeTicketModal');
                                        if (changeModal) {
                                            changeModal.remove();
                                        }
                                        // 重新加载车票列表
                                        if (typeof window.ticketApp.loadTickets === 'function') {
                                            window.ticketApp.loadTickets();
                                        }
                                    });
                                } else {
                                    alert('改签成功！您的车票已成功改签，原票已自动退票。');
                                    // 关闭改签模态框
                                    const changeModal = document.getElementById('changeTicketModal');
                                    if (changeModal) {
                                        changeModal.remove();
                                    }
                                    // 重新加载页面（备用方案）
                                    location.reload();
                                }
                            }
                        } else {
                            // 改签失败
                            const errorMsg = response.data ? response.data.message : '未知错误';
                            console.error('改签失败:', errorMsg);

                            if (window.ticketApp && typeof window.ticketApp.showInfoModal === 'function') {
                                window.ticketApp.showInfoModal('改签失败', '改签失败：' + errorMsg);
                            } else {
                                alert('改签失败：' + errorMsg);
                            }
                        }
                    })
                    .catch(error => {
                        console.error('改签请求错误:', error);

                        let errorMessage = '网络错误，请稍后重试';
                        if (error.response) {
                            // 服务器响应错误
                            console.error('服务器错误状态:', error.response.status);
                            console.error('服务器错误数据:', error.response.data);
                            errorMessage = '服务器错误：' + (error.response.data ? error.response.data.message : error.response.status);
                        } else if (error.request) {
                            // 请求未收到响应
                            errorMessage = '网络连接失败，请检查网络后重试';
                        }

                        if (window.ticketApp && typeof window.ticketApp.showInfoModal === 'function') {
                            window.ticketApp.showInfoModal('网络错误', errorMessage);
                        } else {
                            alert('网络错误：' + errorMessage);
                        }
                    });

            } catch (error) {
                console.error('执行改签逻辑时发生错误:', error);
                alert('改签过程发生错误，请重试');
            }
        }

        // 如果页面有header，需要加载header
        if (document.getElementById('header')) {
            fetch('/home/header.html')
                .then(response => response.text())
                .then(data => {
                    document.getElementById('header').innerHTML = data;
                });
        }
    });
</script>
</body>
</html>

